const cp = require('child_process')
const { resolve } = require('path')
const schedule = require('node-schedule')
const sendMail = require('./mailer')
const { io } = require('../app')

const crawl = async () => {
  const script = resolve(__dirname, '../crawler/coin')
  const child = cp.fork(script, [])
  let invoked = false

  child.on('error', err => {
    if (invoked) return
    invoked = true
    console.log(err)
  })

  child.on('exit', code => {
    if (invoked) return
    invoked = true
    if (code === 0) {}
    // console.log(`exit code: ${code}`)
    // let err = code === 0 ? null : new Error('exit code ' + code)
  })

  child.on('message', async data => {
    let { eth, eos, btm, ada } = data.priceObj
    
    console.log(`eth: ${eth} | eos: ${eos} | btm: ${btm} | ada: ${ada}`)
    
    io.sockets.emit('coin update', {
      data: `eth: ${eth} | eos: ${eos} | btm: ${btm} | ada: ${ada}`
    })
    
    if (+eth < 1300) {
      sendMail({
        to: [
          '1243775332@qq.com',
          '956164483@qq.com'
        ],
        subject: `价格预警[eth: ${eth} | eos: ${eos} | btm: ${btm} | ada: ${ada}]`,
        html: `<a href="https://otcbtc.com/sell_offers?currency=eth&fiat_currency=cny&payment_type=all">点击查看</a>`
      }).then(info => {
        console.log(info)
      }).catch(err => {
        console.log(err)
      })
    }
  })
}

let rule = new schedule.RecurrenceRule()
rule.minute = [new schedule.Range(0, 59)]
// rule.second = [new schedule.Range(0, 59)] // [0, 10, 20, 30, 40, 50]
schedule.scheduleJob(rule, () => {
  crawl()
})
